from django_redis import get_redis_connection
from rest_framework import serializers


class ImageCodeCheckSerializer(serializers.Serializer):
    """检验图形验证码的序列化器"""
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)

    def validate(self, attrs):
        image_code_id = attrs.get('image_code_id', '')
        text = attrs.get('text', '')
        print(text)
        # 校验图形验证码是否正确
        redis_conn = get_redis_connection('verify_codes')
        real_image_text = redis_conn.get('img_%s' % image_code_id)
        print(real_image_text, '=======')
        # if real_image_text != text
        # 此时real_image_text已经通过get获取到了，如果在下面校验的话，可能会存在查询不到的情况
        # not real_image_text 就抛出异常了，下面的删除代码就不会执行了
        redis_conn.delete('img_%s' % image_code_id)
        if not real_image_text:
            raise serializers.ValidationError('图形验证码无效')
        real_image_text = real_image_text.decode()
        if real_image_text.lower() != text.lower():
            raise serializers.ValidationError('图形验证码输入错误')
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            raise serializers.ValidationError('验证码发送频繁')

        return attrs





